﻿using System;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DealKhuyenMaiV2.com.Models;
using DealKhuyenMaiV2.com.Helpers;
using MvcReCaptcha;
namespace DealKhuyenMaiV2.com.Controllers
{
    public class AccountController : BaseController
    {
        public MyMembershipProvider MembershipService { get; set; }
        public MyRoleProvider myRoleProvider { get; set; }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {

            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }

            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.Email, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }

                    else
                    {

                        if (myRoleProvider.IsUserInRole(model.Email, "company"))
                        {
                            Response.Cookies["folderImages"].Value = model.Email;                          
                            return RedirectToAction("Index", "Company");
                        }


                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Sai tên đăng nhập/ mật khẩu.");
                }
            }


            return View(model);
        }

        [HttpPost]
        public ActionResult LogOnAdmin(LogOnModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateAdmin(model.Email, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    Response.Cookies["folderImages"].Value = "admin";
                    if (Request.UrlReferrer.Query != "")
                        return Redirect(Request.UrlReferrer.Query.Replace("?ReturnUrl=%2f", "/"));
                    else
                    {

                        return RedirectToAction("Index", "Admin");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Sai tên đăng nhập/ mật khẩu.");
                }
            }
            ViewBag.Error = true;
            return RedirectToAction("Logon", "Admin");

        }
        protected override void Initialize(RequestContext requestContext)
        {
            if (MembershipService == null)
                MembershipService = new MyMembershipProvider();
            if (myRoleProvider == null)
                myRoleProvider = new MyRoleProvider();

            base.Initialize(requestContext);
        }
        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        public ActionResult LogOffAdmin()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Logon", "Admin");
        }
        //
        // GET: /Account/Register

        public ActionResult Register()
        {

            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }

            var typelist = from p in DbConText.TypeAccounts where p.NameTypeAccount != "admin" select p;
            ViewBag.IDType = new SelectList(typelist.ToList(), "IDTypeAccount", "NameTypeAccount", "1");
            return View();
        }

        //
        // POST: /Account/Register
        [CaptchaValidator]
        [HttpPost]
        public ActionResult Register(RegisterModel model, bool captchaValid)
        {
            if (!captchaValid)
            {
                var typelist = from p in DbConText.TypeAccounts where p.NameTypeAccount != "admin" select p;
                ViewBag.IDType = new SelectList(typelist.ToList(), "IDTypeAccount", "NameTypeAccount");
            
                ModelState.AddModelError("", "Bạn đã nhập capcha sai. Xin Vui lòng nhập lại!");
            }
            else
            {
                if (ModelState.IsValid)
                {

                    try
                    {

                        MembershipService.CreateUser(model.Email,model.phonenumber, model.Password, model.IDType, model.AddressReceive, model.FULLNAME, model.Description, model.Latitude, model.Longitude);
                        FormsAuthentication.SetAuthCookie(model.Email, false);

                        if (myRoleProvider.IsUserInRole(model.Email, "company"))
                        {
                            var coursesRoot = Server.MapPath("~/Images/images");
                            var path = Path.Combine(coursesRoot, model.Email);
                            Response.Cookies["folderImages"].Value = model.Email;
                            Utilities.CreateFolder(path);
                            return RedirectToAction("Index", "Company");
                        }
                        return RedirectToAction("Index", "Home");
                    }
                    catch (ArgumentException ae)
                    {

                        ModelState.AddModelError("", ae.Message);
                    }
                }
                // If we got this far, something failed, redisplay form

                var typelist = from p in DbConText.TypeAccounts where p.NameTypeAccount != "admin" select p;
                ViewBag.IDType = new SelectList(typelist.ToList(), "IDTypeAccount", "NameTypeAccount");
            }
            return View();
        }

        [HttpPost]
        public ActionResult UserDetail(Account model)
        {
            Account account = DbConText.Accounts.SingleOrDefault(p => p.Email == User.Identity.Name);
            if (ModelState.IsValid)
            {
                account.AddressReceive = model.AddressReceive;
                account.FullName = model.FullName;
                account.Description = model.Description;
                account.Latitude = model.Latitude;
                account.PhoneNumber = model.PhoneNumber;
                account.Longitude = model.Longitude;
                DbConText.SaveChanges();
                if (myRoleProvider.IsUserInRole(account.Email, "company"))
                {
                    return RedirectToAction("Index", "Company");
                }
                return RedirectToAction("Index", "Home");
            }


            return View(account);

        }
        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    // MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    //changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Mật khẩu hiện tại không đúng hoặc mật khẩu mới không hợp lệ.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        public ActionResult GetPasswordBack()
        {
            return View();
        }
        [HttpPost]
        public ActionResult GetPasswordBack(GetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                String email = model.Email;
                if (MembershipService.UserExists(email))
                {
                    String passwordd = GenerateRandomPassword();
                    if (MembershipService.ChangeResetPassword(email, passwordd))
                    {
                        Utilities.SendEmail(email, "Password mới của bạn là " + passwordd);
                        return  RedirectToAction("LogOn");

                    }

                }
            }
            return View();
        }

        public ActionResult UserDetail()
        {
            Account account = DbConText.Accounts.SingleOrDefault(p => p.Email == User.Identity.Name);
            return View(account);
        }

        // Account/GenerateRandomPassword
        public String GenerateRandomPassword()
        {
            int passwordLength = 8;

            const string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
            string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
            string PASSWORD_CHARS_NUMERIC = "0123456789";
            //string PASSWORD_CHARS_SPECIAL = "*$-+?_&=!%{}/";

            string allowedChars = PASSWORD_CHARS_LCASE + PASSWORD_CHARS_UCASE + PASSWORD_CHARS_NUMERIC;



            char[] chars = new char[passwordLength];
            var rd = new Random();

            for (var i = 0; i < passwordLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            var password = new string(chars);
            return password;
        }
        public class AdminAuthorize : ActionFilterAttribute
        {

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (!filterContext.RequestContext.HttpContext.Request.IsAuthenticated || !Global.myRoleProvider.IsUserInRole(filterContext.RequestContext.HttpContext.User.Identity.Name, "admin"))
                {

                    // Redirect to the needed login page
                    // This can be pulled from config file or anything else
                    filterContext.HttpContext.Response.Redirect("/Admin/Logon?ReturnUrl="
                                            + HttpUtility.UrlEncode(filterContext.HttpContext.Request.RawUrl));
                }

                base.OnActionExecuting(filterContext);
            }
        }
        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Tên đăng nhập đã tồn tại. Vui lòng chọn tên đăng nhập khác";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Địa chỉ e-mail cho tên đăng nhập trên đã được đăng kí. Vui lòng chọn địa chỉ e-mail khác.";

                case MembershipCreateStatus.InvalidPassword:
                    return "Mật khẩu không đúng.";

                case MembershipCreateStatus.InvalidEmail:
                    return "Địa chỉ e-mail không đúng";

                case MembershipCreateStatus.InvalidAnswer:
                    return "Câu trả lời không đúng.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "Câu hỏi không đúng.";

                case MembershipCreateStatus.InvalidUserName:
                    return "Tên đăng nhập không đúng.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
